package cn.com.utt.common.protorpc.codec;

import cn.com.utt.common.protorpc.message.RPCMessage;
import cn.com.utt.common.protorpc.proto.ArgProto;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class MessageEncoder extends MessageToByteEncoder<RPCMessage>{

	@Override
	protected void encode(ChannelHandlerContext ctx, RPCMessage msg, ByteBuf out)
			throws Exception {
		if (msg ==null ||msg.getHeader()==null){
			throw new Exception("The encode message is null");
		}
		byte[] header = msg.getHeader().toByteArray();
		ArgProto.Arg req = ArgProto.Arg.parseFrom(header);
		//System.out.println("request encode:"+req.toString());
		//System.out.println("request header:"+Hex.encodeHexString(header));
		//System.out.println("request header len:"+header.length);
		byte[] buf = new byte[8];
		int n = Varint.putSignedVarLong(header.length, buf);
		out.writeBytes(buf, 0, n);
		out.writeBytes(header);
		if (msg.getBody()!=null){
			//System.out.println("write body");
			byte[] body = msg.getBody().toByteArray();
			n = Varint.putSignedVarLong(body.length, buf);
			out.writeBytes(buf, 0, n);
			//System.out.println("request body:"+Hex.encodeHexString(body));
			out.writeBytes(body);
		}else{
			n = Varint.putSignedVarLong(0, buf);
			out.writeBytes(buf, 0, n);
		}
	}
}
